import {Directive, forwardRef, Input} from '@angular/core';
import {NG_VALIDATORS, Validator, AbstractControl, Validators} from "@angular/forms";
import {ValidatorRegexPattern} from "./validator-regex-pattern";

@Directive({
    selector: '[password][formControlName],[password][formControl],[password][ngModel]',
    providers: [
        {provide: NG_VALIDATORS, useExisting: forwardRef(() => PasswordValidator), multi: true}
    ]
})
export class PasswordValidator implements Validator {
    @Input("inputPassword")
    password: string;//如果该值不为空，则校验两次密码是否一致

    validate(c: AbstractControl): { [key: string]: any } {
        if (Validators.required(c) != undefined) {
            return null;
        }

        let value = c.value;
        if (!value) {
            return null;
        }

        //
        if (this.password) {
            return this.password == value ? null : {
                password: {
                    valid: false
                }
            };
        }

        let isValid = ValidatorRegexPattern.password.test(value);

        return isValid ? null : {
            password: {
                valid: false
            }
        };
    }
}
